package com.dk.shiro;

import com.dk.pojo.SslPerson;
import com.dk.service.SslMenuService;
import com.dk.service.SslPersonService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

//userrealm需要继承AuthorizingRealm,实现两个方法,认证和授权
public class UserRealm extends AuthorizingRealm {

    @DubboReference
    private SslPersonService personService;
    @DubboReference
    private SslMenuService menuServiceI;
    //授权逻辑
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("授权");
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        SslPerson person = (SslPerson) SecurityUtils.getSubject().getPrincipal();
        List<String> list = menuServiceI.getMenuById(person.getPid());
        simpleAuthorizationInfo.addStringPermissions(list);
        return simpleAuthorizationInfo;
    }

    // 认证逻辑
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //提取表单提交的用户账号信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        SslPerson person = personService.findPersonByName(token.getUsername());
        if(person == null){
            //如果账号不存在直接返回一个null,shiro会抛出UnknownAccountException未注册异常
            return null;
        }
        return new SimpleAuthenticationInfo(person,person.getPwd(), ByteSource.Util.bytes(person.getSalt()),person.getPname());
    }
}
